<template>
  <!-- 搜索条件 -->
  <el-card class="form-card">
    <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

      <QueryFormItem label="图表样式">
        <el-select v-model="treeChartOrient" placeholder="请选择图表样式">
          <el-option key="vertical" value="vertical" label="从上到下"></el-option>
          <el-option key="horizontal" value="horizontal" label="从左到右"></el-option>
        </el-select>
      </QueryFormItem>

      <QueryFormItem label="展开层数">
        <el-select v-model="treeChartInitialTreeDepth" placeholder="请选择数据展开层数">
          <el-option :key="6" :value="6" label="6"></el-option>
          <el-option :key="12" :value="12" label="12"></el-option>
          <el-option :key="20" :value="20" label="20"></el-option>
          <el-option :key="30" :value="30" label="30"></el-option>
          <el-option :key="50" :value="50" label="50"></el-option>
          <el-option :key="100" :value="100" label="100"></el-option>
          <el-option :key="1000" :value="1000" label="全部"></el-option>
        </el-select>
      </QueryFormItem>

      <QueryFormItem label="点击事件">
        <el-select v-model="treeCheckedSearch" placeholder="请选择点击事件">
          <el-option :key="false" :value="false" label="无操作"></el-option>
          <el-option :key="true" :value="true" label="查询数据"></el-option>
        </el-select>
      </QueryFormItem>

      <template #control>
        <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
        <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
      </template>
    </QueryForm>
  </el-card>

  <!-- 列表数据 -->
  <el-card class="content-card">
    <VChart :loading="loading" :option="teamOption" autoresize class="teamTreeChart" @click="handleTreeChartClick"/>
  </el-card>
</template>

<script lang="tsx" setup>
import { computed, provide, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import useTable from '@/hooks/use-table.ts';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { userTeamTreeList } from '@/api/api-user.ts';

import VChart, { THEME_KEY } from 'vue-echarts';
import { useDark } from '@vueuse/core';
import '@/utils/echarts';

const isDark = useDark();
const eChartTheme = computed(() => (isDark.value ? 'dark' : ''));
provide(THEME_KEY, eChartTheme);

// 查询
const queryFormData = reactive({
  account: undefined,
  tree_depth: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
  {type: 'input', prop: 'tree_depth', label: '查询层数', placeholder: '请输入查询层数', clearable: true, inputType: 'number'},
]);

const [loading, setLoading] = useLoading(false);
const {tableMethods} = useTable(() => handleSearch, queryFormRef, false);
const {handleResetForm} = tableMethods;
const treeChartOrient = ref('vertical');
const treeCheckedSearch = ref(false);
const treeChartInitialTreeDepth = ref(6);

// 刷新数据
const handleSearch = async () => {
  if (!queryFormData.account || loading.value) {
    return
  }
  setLoading(true);
  try {
    // 查询数据
    const {data} = await userTeamTreeList({
      ...queryFormData,
    });
    teamData.value = data || [];
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 重置查询条件
const handleResetQueryForm = () => {
  teamData.value = [];
  treeChartOrient.value = 'vertical';
  treeCheckedSearch.value = false;
  treeChartInitialTreeDepth.value = 6;
  handleResetForm();
};

const eChartOptionsFactory = () => {
  const data = ref<any>([]);
  const option = computed(() => {

    // 判断显示方式
    let vertical = treeChartOrient.value === 'vertical';

    // 封装树图数据
    return {
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove',
        formatter: handleTreeChartFormatter
      },
      series: [
        {
          type: 'tree',
          data: data.value,
          top: vertical ? '8%' : '1%',
          left: vertical ? '2%' : '8%',
          right: vertical ? '2%' : '20%',
          bottom: vertical ? '20%' : '1%',
          symbol: 'circle', // emptyCircle
          symbolSize: 9,
          orient: treeChartOrient.value,
          label: {
            position: vertical ? 'top' : 'left',
            verticalAlign: 'middle',
            align: 'right',
            fontSize: 13
          },
          leaves: {
            label: {
              position: vertical ? 'bottom' : 'right',
              rotate: vertical ? -90 : 0,
              verticalAlign: 'middle',
              align: 'left'
            }
          },
          emphasis: {
            focus: 'descendant',
          },
          expandAndCollapse: true,
          initialTreeDepth: treeChartInitialTreeDepth.value || 6, // 树图初始展开的层级（深度）
          animationDuration: 550,
          animationDurationUpdate: 750
        }
      ]
    };
  });
  const handleTreeChartFormatter = (params: any) => {
    let data = params.data
    return '<div style="display:flex;flex-direction:row;">' +
        '  <div style="display:flex;flex-direction:column;">' +
        '    <span>用户编号：' + data.user_id + '</span>' +
        '    <span>用户账号：' + data.account + '</span>' +
        '    <span>用户级别：' + data.user_level + '</span>' +
        '    <span>团队人数：' + data.team_count + '</span>' +
        '    <span>直推人数：' + data.directly_count + '</span>' +
        '  </div>' +
        '</div>'
  };
  return {data, option};
};
const {data: teamData, option: teamOption} = eChartOptionsFactory();

const handleTreeChartClick = (params: any) => {
  if (treeCheckedSearch.value && !loading.value) {
    let data = params.data;
    queryFormData.account = data.account;
    handleSearch();
  }
};
</script>

<style lang="scss" scoped>
.teamTreeChart {
  min-height: 62vh;
}
</style>

